package me.zingon.WebSocket.ws;

import me.zingon.WebSocket.tools.TankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

/**
 * Created by zhidi on 2016-12-21.
 */
public class TankWS extends AbstractWebSocketHandler {

    @Autowired
    TankService tankService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String[] params=session.getUri().getQuery().split("=");
        //p[0]:name ; p[1]:reqId
        String[] p=params[1].split("_");
        if(p[0].length()>5)
            p[0]=params[0].substring(0,5);
        session.getAttributes().put("reqId",p[1]);
        tankService.addPlayer(p[0],p[1],session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        tankService.rmPlayer((String) session.getAttributes().get("reqId"));
        System.out.println((String) session.getAttributes().get("reqId")+" tkws_closing..");
    }
}
